package com.thread;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.concurrent.Callable;

import com.http.HTTPRequester;
import com.http.HTTPResult;
import com.interf.Constant;
import com.interf.IRemoteRequester;

public class ThreadHTTPRequester implements Callable<HTTPResult> {
	private HTTPRequester mTask;
	private String mHostName;
	private int mNumThread;
	private long mOffsetTime;
	private long mTimetoTest;
	
	public ThreadHTTPRequester(HTTPRequester task, String hostName, int numThread, long offsetTime, long timetoTest) {
		mTask = task;
		mHostName = hostName;
		mNumThread = numThread;
		mOffsetTime = offsetTime;
		mTimetoTest = timetoTest;
	}

	@Override
	public HTTPResult call() throws Exception {
		HTTPResult result = new HTTPResult();
		result.threadTime = 0;
		try {
			Registry registry = LocateRegistry.getRegistry(mHostName, Constant.RMI_PORT);
			IRemoteRequester rexecuter = (IRemoteRequester) registry.lookup(Constant.RMI_ID);
			ArrayList<HTTPResult> httpResult = rexecuter.makeRequest(mTask, mNumThread, mOffsetTime, mTimetoTest);
			result.minTime = result.maxTime = httpResult.get(0).threadTime;
			result.totalTime = 0;
			for (HTTPResult item : httpResult) {
				if (item.threadTime > result.maxTime) {
					result.maxTime = item.threadTime;
				}
				if (item.threadTime < result.minTime) {
					result.minTime = item.threadTime;
				}
				result.totalTime += item.threadTime;
			}
			
			// Return average time;
			result.averageTime = result.totalTime / httpResult.size();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
